/**
 * Created by spatra on 14-12-3.
 */

define(['projectJS/module'], function(projectModule){

  /**
   * 用于处理用户项目列表的控制器
   */
  projectModule.controller('ProjectListController', ['$scope', 'projectList',
    function($scope, projectList){
      $scope.projects = projectList;

  }]);  //End of --> ProjectListController

  /**
   * 工作台控制器
   */
  projectModule.controller('ProjectDesktopController', ['$scope', '$modal', '$stateParams', 'TaskService','MemberService', 'taskSet', 'currentProjectInfo',
    function($scope, $modal, $stateParams, TaskService, MemberService, taskSet, currentProjectInfo){
      $scope.taskFirstLevelList = taskSet;
      $scope.currentProjectInfo = currentProjectInfo;

      //根据$stateParams设置父级资源Project的id
      TaskService.accessor['setParentResourceId']($stateParams);
      MemberService.accessor['setParentResourceId']($stateParams);

      //根据节点的id获取其状态id
      function getStatusId(id){
        for(var i=0;i<$scope.taskFirstLevelList.length;i++){
          if($scope.taskFirstLevelList[i].id == id){
            return $scope.taskFirstLevelList[i].status_id;
          }
        }
        return null;
      }


      $scope.deleteTask = function(id) {
        var nodeStatusId = getStatusId(id);

        TaskService.accessor.destroy(id)
          .success(function(){
            $scope.handleNode.deleteNode();
            $scope.$emit('message:success', {
              title: '任务删除成功'
            });
            $scope.$emit('task:reload', {
              currentStatusId: nodeStatusId
            });

          })
          .error(function(data){
            $scope.$emit('message:error', {
              title: '删除任务失败',
              msg: data.error
            });
            console.error(data.error);
          })
      };


      $scope.createTask = function(parentTaskInfo) {

        $scope.createTaskModalInstance = $modal.open({
          templateUrl: 'ngApp/project/tpls/createTaskModal.html',
          controller: 'CreateTaskModalController',
          size: 'lg',
          resolve: {
            parentTaskInfo: function(){
              return parentTaskInfo || null;
            },
            projectMemberList: function(){
              return MemberService.accessor.get()
                .then(function(resp){
                  var projectMembers = resp.data.members;
                  projectMembers.unshift(resp.data.creater);
                  return projectMembers;
                },
                  function(resp) {
                    console.error(resp.data);
                    $scope.$emit('message:error',{
                      title: '加载成员列表出错'
                    })
                  });
            },
            priorityList: ['TaskPriorityService', function(TaskPriorityService){
              return TaskPriorityService.accessor.get()
                .then(function(resp){
                  return resp.data;
                }, function(resp){
                  console.error(resp.data);
                  $scope.$emit('message:error',{
                    msg: '加载任务优先级出错'
                  });
                })
            }]
          }
        });

        $scope.createTaskModalInstance.result
          .then(function (taskData) {
            //设置新添加节点的parent_id
            if(parentTaskInfo) {
              taskData.parent_id = parentTaskInfo.id;
            }

            TaskService.accessor.store(taskData)
              .success(function (data) {
                $scope.handleNode.addNode(taskData.name, data.id);
                $scope.$emit('message:success',{
                  title: '任务创建成功'
                });
                $scope.$emit('task:reload', {
                  //@workaround:暂时设死为1
                  currentStatusId: 1
                });
              })
              .error(function () {
                $scope.$emit('message:error',{
                  title: '任务创建失败'
                });
              });
          });
      };//End of the $scope.createTask function

  }]);// End of --> ProjectDesktopController

  /**
   * 项目设置的控制器
   */
  projectModule.controller('ProjectSettingController', ['$scope', '$stateParams', '$location', 'ProjectService', 'currentProjectInfo',
    function($scope, $stateParams, $location, ProjectService, currentProjectInfo){

      /*
      初始化控制器作用域来使用到的变量
       */
      $scope.projectData = currentProjectInfo.baseInfo;  //项目的基本信息
      $scope.editable = currentProjectInfo.editable;     //当前浏览者是否对项目信息拥有修改的权限

      /**
       * 执行更改项目信息的操作
       */
      $scope.submitProject = function(){
        ProjectService.accessor.update($stateParams['projectId'], $scope.projectData)
          .success(function(){
            $scope.$emit('message:success',{
              title: '项目修改成功'
            });
          })
          .error(function(data) {
            console.error(data);
            $scope.$emit('message:error',{
              title: '项目修改失败',
              msg: data.error || ''
            });
          });
      };

      /**
       * 执行删除项目的操作
       */
      $scope.deleteProject = function(){
        if( ! confirm('删除操作不可恢复！ 您确实要执行吗？ ') ) return ;

        ProjectService.accessor.destroy($stateParams['projectId'])
          .success(function(){ $location.path('/project/list'); })
          .error(function(data){ alert( data.error ); });
      };
  }]);//End of --> ProjectSettingController

  /**
   * 项目创建控制器
   * 控制器提供项目创建功能
   */
  projectModule.controller('ProjectCreatingController', ['$scope', '$location', 'ProjectService', 'roleList', 'UserService', 'currUser',
    function ($scope, $location, ProjectService, roleList, UserService, currUser) {

      /*
       初始化控制器作用域来使用到的变量
       */
      $scope.projectData = {
        cover: 'fa-gear',
        memberList: []
      };
      $scope.roleList = roleList;

      /**
       * 添加新的项目成员
       */
      $scope.addMemberInCreate = function(){
        var identify = $.trim( $scope.addMemberIdentify );

        if( identify === currUser['email'] || identify === currUser['username'] ){
          $scope.$emit('message:error',{
            title: '项目成员添加失败',
            msg: '不能添加您自己'
          });
          return ;
        }

        UserService.exist(identify)
          .success(function(data) {
            $scope.projectData.memberList.push({
              'username': data.username,
              'head_image': data.head_image,
              'role_id': $scope.addMemberRole.id,
              'role_label': $scope.addMemberRole.label,
              'user_id': data.id
            });

            $scope.addMemberIdentify = null;
            $scope.hasMember = true;
          })
          .error(function() {
            $scope.$emit('message:error',{
              title: '项目成员添加失败',
              msg: '该成员不存在'
            });
          });
      };

      /**
       * 创建项目，若成功则跳转到新的项目页面
       */
      $scope.createProject = function(){
        ProjectService.accessor.store($scope.projectData)
          .success(function(data){
            $location.path('/project/' + data.id + '/desktop');
          })
          .error(function(){
            $scope.$emit('message:error',{
              title: '项目创建失败',
              msg: data.error
            });
          });
      };
  }]);//End of --> ProjectCreatingController

});